<template>
  <div class="announcements-container">
    <el-card class="announcements-card">
      <template #header>
        <div class="card-header">
          <h2>系统公告</h2>
          <div class="header-actions" v-if="isAdmin">
            <el-button type="primary" size="small" @click="showCreateDialog">
              发布公告
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 置顶公告 -->
      <div class="top-announcements" v-if="topAnnouncements.length > 0">
        <h3>置顶公告</h3>
        <div
          v-for="announcement in topAnnouncements"
          :key="announcement.id"
          class="announcement-item announcement-top"
          @click="viewAnnouncementDetail(announcement.id)"
        >
          <div class="announcement-title">
            <el-tag type="danger" effect="dark">置顶</el-tag>
            <span class="title-text">{{ announcement.title }}</span>
          </div>
          <div class="announcement-meta">
            <span class="meta-item">
              <el-icon><Calendar /></el-icon>
              {{ formatDate(announcement.createTime) }}
            </span>
            <span class="meta-item">
              <el-icon><ViewIcon /></el-icon>
              {{ announcement.viewCount || 0 }} 浏览
            </span>
            <span class="meta-item">
              <el-tag size="small" :type="getTagType(announcement.type)">
                {{ getTypeText(announcement.type) }}
              </el-tag>
            </span>
          </div>
        </div>
      </div>
      
      <!-- 加载中 -->
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="3" animated :count="3" />
      </div>
      
      <!-- 公告列表 -->
      <div v-else>
        <div v-if="announcements.length === 0" class="empty-container">
          <el-empty description="暂无公告" />
        </div>
        <div v-else class="announcements-list">
          <div
            v-for="announcement in announcements"
            :key="announcement.id"
            class="announcement-item"
            @click="viewAnnouncementDetail(announcement.id)"
          >
            <div class="announcement-title">
              <span class="title-text">{{ announcement.title }}</span>
            </div>
            <div class="announcement-meta">
              <span class="meta-item">
                <el-icon><User /></el-icon>
                {{ announcement.publisherName }}
              </span>
              <span class="meta-item">
                <el-icon><Calendar /></el-icon>
                {{ formatDate(announcement.createTime) }}
              </span>
              <span class="meta-item">
                <el-icon><ViewIcon /></el-icon>
                {{ announcement.viewCount || 0 }} 浏览
              </span>
              <span class="meta-item">
                <el-tag size="small" :type="getTagType(announcement.type)">
                  {{ getTypeText(announcement.type) }}
                </el-tag>
              </span>
            </div>
            
            <!-- 管理按钮 -->
            <div v-if="isAdmin" class="announcement-actions" @click.stop>
              <el-button 
                type="primary" 
                size="small" 
                plain
                @click.stop="editAnnouncement(announcement)"
              >
                编辑
              </el-button>
              <el-button 
                type="danger" 
                size="small" 
                plain
                @click.stop="confirmDelete(announcement.id)"
              >
                删除
              </el-button>
            </div>
          </div>
        </div>
        
        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            background
            layout="prev, pager, next"
            :total="total"
            :page-size="pageSize"
            :current-page="currentPage"
            @current-change="handlePageChange"
          />
        </div>
      </div>
    </el-card>
    
    <!-- 公告详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      :title="currentAnnouncement.title"
      width="700px"
      destroy-on-close
    >
      <div class="announcement-detail">
        <div class="announcement-info">
          <span class="info-item">
            <el-icon><User /></el-icon>
            发布者: {{ currentAnnouncement.publisherName }}
          </span>
          <span class="info-item">
            <el-icon><Calendar /></el-icon>
            发布时间: {{ formatDate(currentAnnouncement.createTime) }}
          </span>
          <span class="info-item">
            <el-icon><ViewIcon /></el-icon>
            浏览量: {{ currentAnnouncement.viewCount || 0 }}
          </span>
          <span class="info-item">
            <el-tag size="small" :type="getTagType(currentAnnouncement.type)">
              {{ getTypeText(currentAnnouncement.type) }}
            </el-tag>
          </span>
        </div>
        <div class="announcement-content" v-html="formattedContent"></div>
      </div>
    </el-dialog>
    
    <!-- 创建/编辑公告对话框 -->
    <el-dialog
      v-model="editVisible"
      :title="isEdit ? '编辑公告' : '发布公告'"
      width="700px"
      destroy-on-close
    >
      <el-form :model="announcementForm" ref="announcementFormRef" :rules="announcementRules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="announcementForm.title" placeholder="请输入公告标题" />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input
            v-model="announcementForm.content"
            type="textarea"
            :rows="10"
            placeholder="请输入公告内容"
          />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="announcementForm.type" placeholder="请选择公告类型">
            <el-option label="普通公告" value="notice" />
            <el-option label="重要公告" value="important" />
            <el-option label="系统公告" value="system" />
          </el-select>
        </el-form-item>
        <el-form-item label="置顶">
          <el-switch v-model="announcementForm.isTop" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editVisible = false">取消</el-button>
          <el-button type="primary" :loading="submitting" @click="submitAnnouncement">
            {{ isEdit ? '保存' : '发布' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, onMounted, watch } from 'vue'
import { useStore } from 'vuex'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import moment from 'moment'
import api from '@/api'
import {
  Calendar,
  View as ViewIcon,
  User,
} from '@element-plus/icons-vue'

export default {
  name: 'Announcements',
  components: {
    Calendar,
    ViewIcon,
    User,
  },
  setup() {
    const store = useStore()
    const route = useRoute()
    
    // 数据初始化
    const loading = ref(true)
    const announcements = ref([])
    const topAnnouncements = ref([])
    const total = ref(0)
    const currentPage = ref(1)
    const pageSize = ref(10)
    const detailVisible = ref(false)
    const currentAnnouncement = ref({})
    const editVisible = ref(false)
    const isEdit = ref(false)
    const submitting = ref(false)
    
    // 表单相关
    const announcementFormRef = ref(null)
    const announcementForm = ref({
      title: '',
      content: '',
      type: 'notice',
      isTop: 0
    })
    const announcementRules = {
      title: [
        { required: true, message: '请输入公告标题', trigger: 'blur' },
        { min: 2, max: 100, message: '标题长度应在2-100个字符之间', trigger: 'blur' }
      ],
      content: [
        { required: true, message: '请输入公告内容', trigger: 'blur' }
      ],
      type: [
        { required: true, message: '请选择公告类型', trigger: 'change' }
      ]
    }
    
    // 计算属性
    const isAdmin = computed(() => {
      return store.getters['user/isAdmin'];
    });
    
    const formattedContent = computed(() => {
      if (!currentAnnouncement.value.content) return '';
      
      // 简单处理换行，更复杂的富文本可以使用插件处理
      return currentAnnouncement.value.content.replace(/\n/g, '<br>');
    });
    
    // 方法定义
    const formatDate = (date) => {
      if (!date) return '';
      return moment(date).format('YYYY-MM-DD HH:mm');
    };
    
    const getTypeText = (type) => {
      switch (type) {
        case 'notice': return '普通公告';
        case 'important': return '重要公告';
        case 'system': return '系统公告';
        default: return '普通公告';
      }
    };
    
    const getTagType = (type) => {
      switch (type) {
        case 'notice': return 'info';
        case 'important': return 'danger';
        case 'system': return 'warning';
        default: return 'info';
      }
    };
    
    // 获取公告列表
    const fetchAnnouncements = async () => {
      loading.value = true;
      try {
        const params = {
          page: currentPage.value,
          size: pageSize.value
        };
        
        const response = await api.announcement.getList(params);
        if (response && response.code === 0) {
          // 确保每个公告的isTop字段是数字类型
          const announcementsList = response.data || [];
          announcements.value = announcementsList.map(item => ({
            ...item,
            isTop: item.isTop !== null && item.isTop !== undefined ? Number(item.isTop) : 0
          }));
          total.value = response.total || 0;
        } else {
          ElMessage.error(response?.message || '获取公告列表失败');
        }
      } catch (error) {
        console.error('获取公告列表错误:', error);
        ElMessage.error('获取公告列表失败');
      } finally {
        loading.value = false;
      }
    };
    
    // 获取置顶公告
    const fetchTopAnnouncements = async () => {
      try {
        const response = await api.announcement.getTopAnnouncements();
        if (response && response.code === 0) {
          // 确保每个公告的isTop字段是数字类型
          const topList = response.data || [];
          topAnnouncements.value = topList.map(item => ({
            ...item,
            isTop: item.isTop !== null && item.isTop !== undefined ? Number(item.isTop) : 0
          }));
        } else {
          console.warn('获取置顶公告失败:', response?.message);
        }
      } catch (error) {
        console.error('获取置顶公告错误:', error);
      }
    };
    
    // 查看公告详情
    const viewAnnouncementDetail = async (id) => {
      try {
        const response = await api.announcement.getDetail(id);
        if (response && response.code === 0) {
          currentAnnouncement.value = response.data || {};
          detailVisible.value = true;
        } else {
          ElMessage.error(response?.message || '获取公告详情失败');
        }
      } catch (error) {
        console.error('获取公告详情错误:', error);
        ElMessage.error('获取公告详情失败');
      }
    };
    
    // 处理分页
    const handlePageChange = (page) => {
      currentPage.value = page;
      fetchAnnouncements();
    };
    
    // 显示创建公告对话框
    const showCreateDialog = () => {
      isEdit.value = false;
      announcementForm.value = {
        title: '',
        content: '',
        type: 'notice',
        isTop: 0
      };
      editVisible.value = true;
    };
    
    // 显示编辑公告对话框
    const editAnnouncement = async (announcement) => {
      isEdit.value = true;
      // 先获取最新的公告详情，确保我们获取到最新的置顶状态
      try {
        loading.value = true;
        const response = await api.announcement.getDetail(announcement.id);
        if (response && response.code === 0 && response.data) {
          const announcementData = response.data;
          // 确保isTop是数字类型并转换为整数
          announcementData.isTop = announcementData.isTop !== null && announcementData.isTop !== undefined 
            ? Number(announcementData.isTop) 
            : 0;
            
          console.log('公告详情:', announcementData);
          
          // 使用获取到的最新数据填充表单
          announcementForm.value = {
            id: announcementData.id,
            title: announcementData.title,
            content: announcementData.content,
            type: announcementData.type || 'notice',
            isTop: announcementData.isTop
          };
          editVisible.value = true;
        } else {
          ElMessage.error(response?.message || '获取公告详情失败');
        }
      } catch (error) {
        console.error('获取公告详情错误:', error);
        ElMessage.error('获取公告详情失败');
      } finally {
        loading.value = false;
      }
    };
    
    // 提交公告表单
    const submitAnnouncement = async () => {
      if (!announcementFormRef.value) return;
      
      await announcementFormRef.value.validate(async (valid) => {
        if (!valid) return;
        
        submitting.value = true;
        try {
          // 确保isTop是数字类型
          const formData = { ...announcementForm.value };
          // 确保isTop是整数，强制转换
          formData.isTop = Number(formData.isTop);
          
          let response;
          if (isEdit.value) {
            // 编辑现有公告
            response = await api.announcement.update(formData);
          } else {
            // 创建新公告
            response = await api.announcement.create(formData);
          }
          
          if (response && response.code === 0) {
            ElMessage.success(isEdit.value ? '公告更新成功' : '公告发布成功');
            editVisible.value = false;
            // 刷新数据
            fetchAnnouncements();
            fetchTopAnnouncements();
          } else {
            ElMessage.error(response?.message || (isEdit.value ? '更新公告失败' : '发布公告失败'));
          }
        } catch (error) {
          console.error(isEdit.value ? '更新公告错误:' : '发布公告错误:', error);
          ElMessage.error(isEdit.value ? '更新公告失败' : '发布公告失败');
        } finally {
          submitting.value = false;
        }
      });
    };
    
    // 确认删除公告
    const confirmDelete = (id) => {
      ElMessageBox.confirm('确定要删除这条公告吗？该操作不可恢复。', '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await api.announcement.delete(id);
          if (response && response.code === 0) {
            ElMessage.success('公告删除成功');
            // 刷新数据
            fetchAnnouncements();
            fetchTopAnnouncements();
          } else {
            ElMessage.error(response?.message || '删除公告失败');
          }
        } catch (error) {
          console.error('删除公告错误:', error);
          ElMessage.error('删除公告失败');
        }
      }).catch(() => {
        // 用户取消删除，不做处理
      });
    };
    
    // 处理URL参数中的公告ID
    const handleAnnouncementIdFromQuery = async () => {
      const announcementId = route.query.id;
      if (announcementId) {
        await viewAnnouncementDetail(Number(announcementId));
      }
    };
    
    // 监听路由变化，处理公告ID
    watch(
      () => route.query.id,
      (newId) => {
        if (newId) {
          viewAnnouncementDetail(Number(newId));
        }
      }
    );
    
    // 初始化
    onMounted(() => {
      fetchAnnouncements();
      fetchTopAnnouncements();
      handleAnnouncementIdFromQuery();
    });
    
    return {
      loading,
      announcements,
      topAnnouncements,
      total,
      currentPage,
      pageSize,
      isAdmin,
      detailVisible,
      currentAnnouncement,
      formattedContent,
      editVisible,
      isEdit,
      submitting,
      announcementForm,
      announcementFormRef,
      announcementRules,
      formatDate,
      getTypeText,
      getTagType,
      viewAnnouncementDetail,
      handlePageChange,
      showCreateDialog,
      editAnnouncement,
      submitAnnouncement,
      confirmDelete
    };
  }
};
</script>

<style scoped>
.announcements-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

.announcements-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.top-announcements {
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.top-announcements h3 {
  color: #606266;
  font-size: 18px;
  margin-bottom: 15px;
}

.announcement-item {
  padding: 16px;
  border-bottom: 1px solid #ebeef5;
  cursor: pointer;
  transition: background-color 0.2s;
  position: relative;
}

.announcement-item:hover {
  background-color: #f9fafc;
}

.announcement-top {
  background-color: #fff9f9;
}

.announcement-title {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.title-text {
  margin-left: 8px;
  font-weight: 600;
  font-size: 16px;
  color: #303133;
}

.announcement-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  color: #909399;
  font-size: 13px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.announcement-actions {
  position: absolute;
  right: 16px;
  top: 16px;
  display: flex;
  gap: 8px;
}

.loading-container, .empty-container {
  padding: 20px 0;
  text-align: center;
}

.pagination-container {
  margin-top: 20px;
  text-align: center;
}

.announcement-detail {
  padding: 20px 0;
}

.announcement-info {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
  color: #606266;
  font-size: 14px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.announcement-content {
  line-height: 1.8;
  color: #303133;
  white-space: pre-wrap;
}

@media screen and (max-width: 768px) {
  .announcements-container {
    padding: 10px;
  }
  
  .announcement-meta {
    flex-direction: column;
    gap: 8px;
  }
  
  .announcement-actions {
    position: static;
    margin-top: 15px;
    justify-content: flex-end;
  }
  
  .announcement-info {
    flex-direction: column;
    gap: 10px;
  }
}
</style>